<template>
  <div class="box">
    <div class="lf">
      <!-- 图片上传组件辅助-->
      <div class="btns">
        <el-button size="mini" type="success" @click="sendMail()">发送</el-button>
        <el-button v-if="$route.params.id == 'empty'" size="mini" type="info" plain @click="toDrafts(false)">存草稿箱</el-button>
        <el-button size="mini" type="info" plain @click="goback()">取消</el-button>
      </div>
      <div class="top_info">
        <div class="item">
          <label class="red"><span>收件人</span>：</label>
          <el-input class="bg_f" v-model="person" disabled="" placeholder="根据右侧列表，点击选择联系人"></el-input>
        </div>
        <div class="item">
          <label>主&nbsp;&nbsp;&nbsp;&nbsp;题&nbsp;&nbsp;：</label>
          <el-input class="bg_f" v-model="title"></el-input>
        </div>
      </div>
      <el-upload class="avatar-uploader" action="" name="img" :show-file-list="false" :before-upload="beforeUpload">
      </el-upload>
      <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @change="onEditorChange($event)">
      </quill-editor>
      <div class="btns">
        <el-button size="mini" type="success" @click="sendMail()">发送</el-button>
        <el-button size="mini" type="info" plain @click="goback()">取消</el-button>
      </div>
    </div>
    <div class="rt">
      <p>联系人列表</p>
      <div class="list">
        <div class="item" v-for="(item, index) in userList" :key="index" @click="getUser(item)">
          {{item.nick}}&nbsp;&nbsp;-&nbsp;&nbsp;{{item.mobile}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Quill from 'quill';
  import ImageResize from 'quill-image-resize-module';
  Quill.register('modules/imageResize', ImageResize);
  import {
    userUpload,
    mailAdd,
    mailDet,
    toMail,
    userList
  } from '../../apis/api.js'
  import { storage } from '../../utils/storage.js'
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike', {
      'list': 'ordered'
    }, {
      'list': 'bullet'
    }],
    [{
      'indent': '-1'
    }, {
      'indent': '+1'
    }],
    [{
      'direction': 'rtl'
    }],
    [{
      'align': []
    }],
    [{
      'font': []
    }],
    [{
      'header': [1, 2, 3, 4, 5, 6, false]
    }],
    [{
      'color': []
    }, {
      'background': []
    }],
    ['link', 'image'],
    ['clean']
  ]
  export default {
    data() {
      return {
        file: '',
        person: '',
        personId: '',
        title: '',
        mailId: null,
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        content: null,
        editorOption: {
          modules: {
            imageResize: true,
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function (value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        userList: [],
        userListOk: false,
        total: 0,
        pageNum: 1,
        pageSize: 10
      }
    },
    watch: {
      userListOk(val) {
        console.log('获取det')
        this.getDet();
      }
    },
    methods: {
      sendMail() {
        if(this.$route.params.id == 'empty') {
          console.log('add')
          if(!this.personId) {
            return this.$message.warning('请点击选择收件人')
          }
          if(!this.title && !this.content) {
            return this.$message.warning('请输入邮件主题或内容')
          }
          mailAdd({
            content: this.content,
            title: this.title,
            toUserId: this.personId,
            type: '1',
            userId: storage.getSession('id')
          }).then(res => {
            console.log(res)
            this.$message.success('邮件发送成功')
            setTimeout(() => {
              this.$router.replace('/send')
            })
          })
        } else {
          console.log('toMail')
          toMail({
            content: this.content,
            mailId: this.$route.params.id,
            title: this.title,
            toUserId: this.personId
          }).then(res => {
            console.log(res)
            this.$message.success('邮件发送成功')
  
          })
        }
      },
      getUser(item) {
        if(this.$route.params.id == 'empty' || !this.personId) {
          console.log(item)
          this.person = item.nick;
          this.personId = item.id;
        } else {
          // if(this.personId) {
            this.$message.warning('草稿箱文件禁止编辑收件人')
          // }
        }
      },
      onEditorChange({
        editor,
        html,
        text
      }) { //内容改变事件
        this.content = html
        console.log(html)
      },
      // 富文本图片上传前
      beforeUpload(file) {
        console.log(file)
        var formData = new FormData();
        formData.append("file", file);
        console.log(formData)
        userUpload(formData).then(res => {
          console.log(res)
          // this.file = res.filePath;
          this.insertImg(res.filePath)
        })
      },
      insertImg(filePath) {
        // 获取富文本组件实例
        let quill = this.$refs.myQuillEditor.quill
        // 获取光标所在位置
        let length = quill.getSelection().index;
        console.log(length)
        // 插入图片  res.url为服务器返回的图片地址
        quill.insertEmbed(length, 'image', filePath)
        // 调整光标到最后
        quill.setSelection(length + 1)
        // // loading动画消失
        // this.quillUpdateImg = false
      },
      getList() {
        userList({
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }).then(res => {
          console.log(res)
          this.total = res.total;
          var index=0;
          for(var i in res.list){
            if(res.list[i]['id']== storage.getSession('id')){
              index=i;
              break;
            }
          }
          res.list.splice(index,1);
          this.userList = res.list;
          if(this.$route.params.id != 'empty') {
            this.userListOk = true;
          }
        })
      },
      toDrafts(isCallback) { // 保存为草稿
        mailAdd({
          content: this.content,
          title: this.title,
          toUserId: this.personId,
          type: '2',
          userId: storage.getSession('id')
        }).then(res => {
          console.log(res)
          this.$message.success('邮件已存入草稿箱');
          if(isCallback) {
            this.callback();
          }
        })
      },
      callback() {
        setTimeout(() => {
          this.$router.go(-1);
        }, 500)
      },
      goback() { // 点击取消编辑
        if(this.$route.params.id!='empty') {
          this.$router.go(-1);
        }else {
          if(this.title||this.content){
            this.$confirm('您正在写信中，是否离开写信页面？', {
              confirmButtonText: '离开并存草稿',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.toDrafts(true)
            }).catch(() => {
              console.log('取消')
            })
          } else {
            this.$router.go(-1);
          }
        }
      },
      getDet() { // 获取草稿箱详情
        mailDet({
          id: this.$route.params.id
        }).then(res => {
          console.log(res)
          this.title = res.title;
          this.mailId = res.id;
          this.content = res.content;
          if(res.toUserId) {
            this.userList.forEach(item => {
              console.log(item)
              if(item.id == res.toUserId) {
                this.person = item.nick;
                this.personId = item.id;
              }
            })
          }
        })
      }
    },
    mounted() {
      this.getList();
      console.log(this.$route.params.id)
      // if(this.$route.params.id != 'empty') {
      //   console.log('from 草稿箱')
      //   this.getDet();
      // }
    },
  }
</script>

<style>
  .box {
    display: flex;
    justify-content: space-between;
  }
  .box .lf {
    flex: 1;
    padding-right: 26px;
    padding-left: 26px;
    border-right: 1px solid #D1D1D1 ;
  }
  .box .rt {
    text-align: left;
    width: 170px;
    padding: 10px 15px 20px;
  }
  .box .rt >p {
    padding-bottom: 10px;
    border-bottom: 1px solid #D1D1D1;
  }
  .rt .list .item {
    line-height: 30px;
    cursor: pointer;
  }
  .rt .list .item:hover {
    color: #951b1b;
  }


  .ql-editor.ql-blank,
  .ql-editor {
    min-height: 440px;
    max-height: 650px;
  }
  .btns {
    margin: 30px 0 0;
    text-align: left;
  }
  .top_info {
    margin-top: 15px;
  }
  .top_info .item {
    padding-left: 57px;
    position: relative;
    height: 40px;
    zoom: 1;
    overflow: visible;
    border-bottom: #ccc 1px solid;
  }
  .top_info .item:hover {
    border-bottom-color: #bbb;
  }
  .top_info .item label {
    position: absolute;
    line-height: 30px;
    left: 0;
    top: 11px;
    white-space: nowrap;
    color: #999;
  }
  .top_info .item label.red {
    color: #951b1b;
  }
  .top_info .item label.red span {
    cursor: pointer;
    padding: 3px 4px;
    border-radius: 3px;
  }
  .top_info .item label.red span:hover {
    background-color: #951b1b;
    color: #fff;
  }
  .top_info .item input {
    border: none;
    padding-left: 10px;
    height: 20px;
    margin-top: 15px;
    line-height: 20px;
    font-size: 12px;
  }
</style>